package ua.pp.bizon.yandex.nb;

import ua.pp.bizon.yandex.api.JobInfo;
import ua.pp.bizon.yandex.api.impl.Activity;
import ua.pp.bizon.yandex.api.impl.Element;
import ua.pp.bizon.yandex.uploader.atom.EntryAlbum;
import ua.pp.bizon.yandex.uploader.atom.Photo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import javax.swing.JOptionPane;

import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;

public class AddPhotosController implements JobInfo {

	private List<File> from;
	private EntryAlbum to;
	private ProgressPanel dialog;
	private AddPhotosDialogData data;

	public AddPhotosController(ProgressPanel dialog, List<File> from, EntryAlbum to) {
		this.dialog = dialog;
		this.from = from;
		this.to = to;
		this.data = dialog.getData();
		dialog.setJob(this);
		LogFactory.getLog(getClass()).trace("new " + toString());
	}

	@Override
	public void run() {
		for (int i = 0; i < from.size(); i++) {
			File fileFrom = from.get(i);
			data.setFrom(fileFrom.getAbsolutePath());
			data.setCountdone(i);
			boolean repeat = true;
			do {
				if (from.isEmpty()) {
					break;
				}
				try {
					Photo photo = to.createPhoto(fileFrom);
					FileOutputStream stream = new FileOutputStream(new File(fileFrom + ".token"));
					stream.write(photo.getElement().toString().getBytes());
					stream.close();
					repeat = false;
				} catch (HttpException e) {
					if (!data.isRepeatOnError()) {
						switch (JOptionPane.showOptionDialog(dialog, "error occured during copy, repeat?", "error", JOptionPane.YES_NO_CANCEL_OPTION,
								JOptionPane.ERROR_MESSAGE, null, new Object[] { "Yes", "Yes to All", "Cancel" }, "Yes")) {
						case JOptionPane.YES_OPTION:
							repeat = true;
							break;
						case JOptionPane.NO_OPTION:
							repeat = true;
							data.setRepeatOnError(true);
						default:
							repeat = false;
							break;
						}
					} else {
						repeat = true;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			} while (repeat);

		}
		dialog.setVisible(false);
		dialog.setJob(null);
	}

	@Override
	public Element getState() {
		Element element = new Element();
		element.setActivity(Activity.UPLOAD);
		element.setProperties(new TreeMap<String, String>());
		element.getProperties().put(Element.PROP_FROM, data.getFrom());
		element.getProperties().put(Element.PROP_TO, data.getTo());
		element.getProperties().put(Element.PROP_COUNT_DONE, data.getCountdone() + "");
		element.getProperties().put(Element.PROP_COUNT_TOTAL, data.getTotalcount() + "");
		return element;
	}

	public void cancel() {
		from.clear();
	}
}
